import 'dart:async';
import 'package:base_lib/common/bloc/base_bloc.dart';
import 'package:base_lib/router/index.dart';
import 'package:base_lib/utils/shared_preference_util.dart';
import 'package:base_lib/utils/toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:doctor_login_lib/cache/userinfo_cache.dart';
import 'package:doctor_login_lib/repository/http.dart';
import 'package:rxdart/rxdart.dart';
import '../component.dart';

class ForgotPasswordBloc extends BaseBloc {
  PublishSubject<int> sentSmsCount = PublishSubject();
  int _sentSmsCount = 0;
  String _smsCode = '';
  StreamSubscription _sentSmsCountSubscription;

  PublishSubject historyPhone = PublishSubject<String>();
  String _phone = "";

  PublishSubject<int> registerStep = PublishSubject();

  PublishSubject<bool> loadingStatus = PublishSubject();

  @override
  void dispose() {
    sentSmsCount?.close();
    _sentSmsCountSubscription?.cancel();
    historyPhone.close();
    registerStep?.close();
    loadingStatus?.close();
  }

  void editPhoneChanged(String value) {
    _phone = value;
  }

  void smsCodeChanged(String value) {
    _smsCode = value;
  }

  ///发送验证码
  void sentSms() async {
    if (_phone.isEmpty) {
      ToastUtil.show("请输入手机号码!");
      return;
    }
    if (_sentSmsCount != 0) return;
    loadingStatus.add(true);
    var body = await LoginHttp.getCode(_phone);
    loadingStatus.add(false);
    if (!body.isSuccess) {
      ToastUtil.show(body.error.msg);
      return;
    } else {
      ToastUtil.show(body.error.msg);
    }
    _sentSmsCount = 60;
    _sentSmsCountSubscription = Stream.periodic(Duration(seconds: 1))
        .map((value) => _sentSmsCount - 1)
        .listen((value) {
      _sentSmsCount = value;
      sentSmsCount.add(_sentSmsCount);
      if (_sentSmsCount == 0) _sentSmsCountSubscription.cancel();
    });
  }

  ///设置手机号
  void setPhone(BuildContext context) async {
    if (_phone.isEmpty) {
      ToastUtil.show("请输入手机号码!");
      return;
    }
    if (_smsCode.isEmpty) {
      ToastUtil.show("请输入手机号码!");
      return;
    }
    loadingStatus.add(true);
    var result = await LoginHttp.doctorLoginByCode(_phone, _smsCode);
    loadingStatus.add(false);
    if (result.isSuccess) {
      Routers.navigateTo(context, DoctorLoginComponent.setLoginPasswordPage,
          parameters: Parameters()..putString("phone", _phone));
    } else {
      ToastUtil.show(result?.error?.msg ?? "");
    }
  }
}
